package com.esunny.online.aspect;

import com.esunny.online.annotation.OperationLogAnnotation;
import com.esunny.online.dao.OperationLogDao;
import com.esunny.online.domain.entity.OperationLog;
import com.esunny.online.util.HostHolder;
import com.esunny.online.util.HttpContextUtils;
import com.esunny.online.util.IPUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Bcc
 * @Date: 2020/8/25 11:37
 * @Description:
 * @modified By:
 * @version: $
 */

@Aspect
@Component
public class OperationLogAspect {

    @Resource
    private OperationLogDao operationLogDao;

    @javax.annotation.Resource
    private HostHolder hostHolder;

    @Value("${online.version}")
    private String version;

    @Pointcut("@annotation(com.esunny.online.annotation.OperationLogAnnotation)")
    public void pointcut() { }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        saveLog(point, time);
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperationLog operationLog = new OperationLog();
        OperationLogAnnotation logAnnotation = method.getAnnotation(OperationLogAnnotation.class);
        if (logAnnotation != null) {
            // 注解上的url
            operationLog.setUrl(logAnnotation.url());
            // 注解上的模块
            operationLog.setOperationmodul(logAnnotation.modul());
            // 注解上的类型
            operationLog.setOperationtype(logAnnotation.type());
            // 注解上的描述
            operationLog.setOperationdescription(logAnnotation.description());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        operationLog.setMethod(className + "." + methodName + "()");
        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();
        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        // 获取登录用户名和密码
        Map<String,Object> map = new HashMap<>(0);
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";

            for (int i = 0; i < args.length; i++) {
                if (paramNames[i].equals("map")){
                    map = (Map<String, Object>) args[i];
                }
                // params += "  " + paramNames[i] + ": " + args[i];
            }
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        operationLog.setIp(IPUtils.getIpAddr(request));
        if(hostHolder.getUser() != null){
            // 设置用户名
            operationLog.setUsername(hostHolder.getUser().getUsername());
            // 设置用户真实姓名
            operationLog.setRealname(hostHolder.getUser().getRealname());
            System.out.println(hostHolder.getUser().toString());
        }else{
            System.out.println("hostHold里面没有user用户");
            operationLog.setUsername((String) map.get("username"));
        }
        // 设置操作执行总时间
        operationLog.setRuntime(time+"");
        // 设置当前操作版本号
        operationLog.setVersion(version);
        // 设置操作开始执行时间
        operationLog.setCreatedtime(new Date());
        // 保存系统日志
        operationLogDao.saveOperationLog(operationLog);
    }

}
